package czk.concrent.enjoyModelWithNotLock.atomicInterger.practice;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/12/16 14:16
 */
public class AtomicIntegerDemo {
    public static void main(String[] args) throws InterruptedException {
        SafeCount safeCount=new SafeCount(new AtomicInteger(100000));
        Account.start(safeCount);
        System.out.println(safeCount.getBalance());
    }
}

/**
 * 线程安全的账户
 */
class SafeCount implements Account{
    private AtomicInteger count;

    public SafeCount(AtomicInteger count) {
        this.count = count;
    }

    @Override
    public int getBalance() {
        return count.get();
    }

    @Override
    public void withDraw(int money) {
        while (true){
            // 拿到现在的
            int pre = count.get();
            //
            int newCount=pre-money;
            if (count.compareAndSet(pre,newCount)){
                break;
            }
        }

    }
}
/**
 * 账户接口
 */
interface Account{
    public Integer threadNum=1000;
    /**
     * 获取余额
     * @return
     */
    int getBalance();

    /**
     * 扣减余额
     * @param money
     */
    void withDraw(int money);

    /**
     * 多线程来调用扣减余额
     * @param account
     */
    static void start(Account account) throws InterruptedException {
        List<Thread> list=new ArrayList<>(10);
        for (int i = 0; i < threadNum; i++) {
            list.add(new Thread(()->{
                account.withDraw(10);
            }));
        }
        // 启动流程
        for (Thread thread : list) {
            thread.start();
        }
        for (Thread thread : list) {
            thread.join();
        }
    }
}
